/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.web.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

/**
 * @author Arisgo
 * @since 2024/6/11
 */
public class ServletUtil {

    private static final Logger logger = LoggerFactory.getLogger(ServletUtil.class);

    public static final ObjectMapper MAPPER = new ObjectMapper();

    public static void sendResponseError(HttpServletResponse response, String path, HttpStatus status) {
        response.setStatus(status.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        try {
            MAPPER.writeValue(response.getWriter(), buildResponseBody(path, status));
        } catch (IOException e) {
            logger.error(status.getReasonPhrase(), e);
        }
    }

    public static Map<String, Object> buildResponseBody(String path, HttpStatus status) {
        return buildResponseBody(path, status.value(), status.getReasonPhrase());
    }

    public static Map<String, Object> buildResponseBody(Object path, Object status, Object msg) {
        Map<String, Object> result = Maps.newLinkedHashMap();
        result.put("code", status);
        result.put("msg", msg);
        result.put("path", path);
        result.put("timestamp", new Date());
        return result;
    }

}
